<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/15 0015
 * Time: 上午 10:13
 */
namespace app\admin\service;

use app\admin\model\OrderAfterSale;
use app\admin\model\Orderitem;
use app\admin\model\Rechargerecord;
use app\api\service\alipay\BasePay;
use app\common\DictConstant;
use app\common\model\Order;
use think\Db;
use think\Exception;
use think\Loader;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');
class Aftersale{
    private $aftersale_id;
    private $info = ['pass'=>true,'msg'=>''];

    function __construct($postdata)
    {
        $this->aftersale_id = $postdata['id'];
    }

    public function actionrefund(){
        $refundorder = OrderAfterSale::where('id',$this->aftersale_id)->find();
        if(!$refundorder){
            $this->info['pass'] = false;
            $this->info['msg'] = '售后订单不存在';
            return $this->info;
        }
        if(in_array($refundorder->status,[2,6])){
            //售后订单状态必须是 同意售后待退款 或者 同意售后已收货
            $order = Order::where('id',$refundorder->order_id)->find();
            $payMethod = $order->pay_method;
            if(!$this->ActiveRefund($refundorder,$payMethod)){
                $this->info['pass'] = false;
                $this->info['msg'] = '退款失败';
                return $this->info;
            }
            return $this->info;
        }else{
            $this->info['pass'] = false;
            $this->info['msg'] = '售后订单状态异常，不能退款';
            return $this->info;
        }
    }


    private function ActiveRefund($refundorder,$payMethod){
        if($payMethod == 1){
            //微信支付
            return $this->Refund($refundorder->out_refund_no);
        }elseif ($payMethod == 2){
            //支付宝
            $Orderitem = Orderitem::where('id',$refundorder->order_item_id)->field('product_name')->find();
            $ailipay = new BasePay();
            $data = $ailipay->refund($Orderitem->product_name,$Orderitem->product_name,$refundorder->out_refund_no,$refundorder->refund_fee);
            if($data['code'] == '10000' && $data['msg'] == 'Success'){
                $this->AliRefundSuccess($data);
                return true;
            }else{
                return false;
            }
        }
        else{
            //账户余额支付
            return $this->balanceRefund($refundorder->out_refund_no);
        }

    }

    private function balanceRefund($out_refund_no){
        Db::startTrans();
        try{
            $refundorder = OrderAfterSale::where(['out_refund_no'=>$out_refund_no])->find();
            $refund_fee = $refundorder->refund_fee;
            $endDate = date('Y-m-d H:i:s',time());
            $refundorder->end_date = $endDate;
            $refundorder->refund_channel = 1;
            $refundorder->status = DictConstant::AfterSale_Success;
            $refundorder->save();
            Orderitem::where('id',$refundorder['order_item_id'])->update(['after_sale_status'=>4]);
            //退余额
            \app\admin\model\Member::where('account_number',$refundorder->member_phone)->setInc('balance',$refund_fee);
            //插入余额消费明细
            $Order = Order::where('id',$refundorder['order_id'])->field('order_no,member_id')->find();
            $this->insertDetailed($Order,$refund_fee);
            Db::commit();
            return true;
        }catch (Exception $ex){
            Db::rollback();
            return false;
        }
    }



    private function Refund($out_refund_no){
        $refundorder = OrderAfterSale::where(['out_refund_no'=>$out_refund_no])->find();
        $refund_fee = $refundorder->refund_fee;
        $wxRefundData = new \WxPayRefund();
        $wxRefundData->SetTotal_fee($refundorder->old_total);
        $wxRefundData->SetOut_trade_no($refundorder->order_id);
        $wxRefundData->SetOut_refund_no($out_refund_no);
        $wxRefundData->SetRefund_fee($refund_fee);
        return $this->WxRefund($wxRefundData);
    }

    private function WxRefund($wxRefundData){
        $wxRefund = \WxPayApi::refund($wxRefundData);
        if($wxRefund['return_code'] == 'SUCCESS' && $wxRefund['result_code'] == 'SUCCESS'){
            //微信退款成功后的处理逻辑
            $this->WxRefundSuccess($wxRefund);
            return true;
        }else{
            return false;
        }
    }

    private function WxRefundSuccess($wxRefund){
//        <xml>
//       <return_code><![CDATA[SUCCESS]]></return_code>
//       <return_msg><![CDATA[OK]]></return_msg>
//       <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
//       <mch_id><![CDATA[10000100]]></mch_id>
//       <nonce_str><![CDATA[NfsMFbUFpdbEhPXP]]></nonce_str>
//       <sign><![CDATA[B7274EB9F8925EB93100DD2085FA56C0]]></sign>
//       <result_code><![CDATA[SUCCESS]]></result_code>
//       <transaction_id><![CDATA[1008450740201411110005820873]]></transaction_id>
//       <out_trade_no><![CDATA[1415757673]]></out_trade_no>
//       <out_refund_no><![CDATA[1415701182]]></out_refund_no>
//       <refund_id><![CDATA[2008450740201411110000174436]]></refund_id>
//       <refund_channel><![CDATA[]]></refund_channel>
//       <refund_fee>1</refund_fee>
//        </xml>
        Db::startTrans();
        try{
            $mch_id = $wxRefund['mch_id'];
            $refund_id = $wxRefund['refund_id'];
            $endDate = date('Y-m-d H:i:s',time());
            $refundorder = OrderAfterSale::where('out_refund_no','=',$wxRefund['out_refund_no'])->find();
            $refundorder->refund_id = $refund_id;
            $refundorder->op_user_id = $mch_id;
            $refundorder->end_date = $endDate;
            $refundorder->refund_channel = 0;
            $refundorder->status = 7;
            $refundorder->save();
            Orderitem::where('id',$refundorder->order_item_id)->update(['after_sale_status'=>4]);
            Db::commit();
        }catch (Exception $ex){
            Db::rollback();
            Log::record($ex);
        }

    }

    private function AliRefundSuccess($data){
        Db::startTrans();
        try{
            $refundorder = OrderAfterSale::where('out_refund_no',$data['trade_no'])->find();
            $refundorder->end_date = $data['gmt_refund_pay'];
            $refundorder->refund_channel = 0;
            $refundorder->status = 7;
            $refundorder->save();
            Orderitem::where('id',$refundorder->order_item_id)->update(['after_sale_status'=>4]);
            Db::commit();
        }catch (Exception $ex){
            Db::rollback();
            Log::record($ex);
        }


    }
    private function insertDetailed($Order,$refund_fee){
        $model = new Rechargerecord();
        $model->order_no = $Order->order_no;
        $model->member_id = $Order->member_id;
        $model->record_money = $refund_fee;
        $model->type = 3;
        $model->detail = '订单售后退款';
        $model->pay_method = 3;
        $model->status = 1;
        $model->save();
    }



}